var mongoose = require('mongoose');
var async = require('async');
const DataModel = require('../models/news.model');
const Comment = require('../models/comment.model');

//保存信息到数据库
exports.create= function (req,res,next) {
    const dataModel = new DataModel(req.body);
    dataModel.save()
        .then(data=>{
        res.json(data);
    })
}

//从数据库中查找信息
exports.get = function (req,res,next) {
    var id = req.params.id;

    DataModel.findById(id, function (err, data) {
        res.json(data);
    })
}

//更改数据库中的信息
exports.update = function (req,res,next) {
    const id = req.params.id;

    DataModel.findByIdAndUpdate(id,{$set:req.body},{new:false})
    //new:false表示找到就更新，找不到就新增
        .then(data=>{
            res.json(data); //输出的是修改前的数据
        })

}

//删除相应的数据
exports.remove = function (req,res,next) {
    const id = req.params.id;

    DataModel.findByIdAndRemove(id,function (err,data) {
        res.json(data);
    })

}

//分页
exports.list = function (req,res,next) {
    var page = (req.body.page)?req.body.page:1;
    var rows = (req.body.rows)?req.body.rows:5;

    var queryCondition = {};

    if(req.body.arr){
        var arr = req.body.arr;

        // ids.split(',').length>0&&ids.split(',')[0]!=''
        if(arr.split(',').length>0){
            DataModel.paginate({cateId:{$in:arr.split(',')}}, { sort:{_id:-1},page: parseInt(page), limit:parseInt(rows)}, function(err, result) {
                result.rows = result.docs;
                delete result.docs;
                res.json(result);
            });
        }
    }
    // if(req.body.name && req.body.name.trim().length>0){
    //     name = req.body.name;
    //     queryCondition = {
    //         "name":new RegExp(name,'i')
    //     }
    // }


    DataModel.paginate(queryCondition, { sort:{_id:-1},page: parseInt(page), limit:parseInt(rows)}, function(err, result) {

        // 评论数获取参考代码
        async.map(result.docs,function(news,done){ // callback修改成done

            Comment.count({newsId: news._id},function(err,count){
                if(err){
                    return;
                }else{
                    news.commentCount = count;
                    done();
                }
            })

        },function(err){

            result.rows = result.docs;
            delete result.docs;
            res.json(result);
        })



    });

}

//删除多条信息
exports.deletes = function (req,res,next){
    var ids = req.body.ids;
    if(ids.length>0){
        console.log(ids.split(','));
        DataModel.remove({_id:{$in:ids.split(',')}})
            .then(data=>{
                res.json({'msg':'delete success','status':200});
            })
    }else{
        res.json({'msg':'deletes fail','status':404});
    }
}